package com.z.sys.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.z.common.aop.enums.LoggingType;
import com.z.common.aop.enums.RequestModel;
import com.z.common.context.UserContext;
import com.z.sys.entity.SysLog;
import com.z.sys.mapper.SysLogMapper;
import com.z.sys.service.SysLogService;
import com.z.common.utils.ServletUtil;
import com.z.common.web.vo.request.PageVo;
import com.z.sys.entity.User;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * Describe: 日 志 服 务 接 口 实 现
 * Author: z
 * CreateTime: 2019/10/23
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper,SysLog> implements SysLogService {

    @Resource
    private SysLogMapper sysLogMapper;


    /**
     * 查询日志
     * @param sysLog 日志
     * @param pageVo
     * @return 日志 分页集合
     * */
    @Override
    public PageInfo<SysLog> selectSysLogPage(SysLog sysLog, PageVo pageVo) {
        PageHelper.startPage(pageVo.getPage(), pageVo.getLimit());
        List<SysLog> data = selectSysLogList(sysLog);
        return new PageInfo<>(data);
    }

    @Override
    public List<SysLog> selectSysLogList(SysLog sysLog) {
        List<SysLog> data = baseMapper.selectSysLogList(sysLog);
        return data;
    }

    @Override
    public boolean save(SysLog sysLog) {
        sysLog.setOperateAddress(ServletUtil.getRemoteHost());
        sysLog.setMethod(ServletUtil.getRequestURI());
        sysLog.setCreateTime(new Date());
        sysLog.setRequestMethod(RequestModel.valueOf(ServletUtil.getMethod()));
        sysLog.setOperateUrl(ServletUtil.getRequestURI());
        sysLog.setBrowser(ServletUtil.getBrowser());
        sysLog.setRequestParam(ServletUtil.getQueryParam());
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        try {
            is = ServletUtil.getRequest().getInputStream();


            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1;)
            {
                sb.append(new String(b, 0, n));
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != is)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        sysLog.setRequestBody(sb.toString());
        sysLog.setSystemOs(ServletUtil.getSystem());
        User currentUser = UserContext.currentUser();
        sysLog.setOperateName(null != currentUser ? currentUser.getUsername() : "未登录用户");
        int result = 0;
        try{
            result = sysLogMapper.insert(sysLog);
        }catch (DataIntegrityViolationException e){
            log.error(e.getMessage());
            int len = sysLog.getResponseBody().length()>1000? 1000: sysLog.getResponseBody().length();
            sysLog.setResponseBody("长度：" + sysLog.getResponseBody().length() + "截取：" + sysLog.getResponseBody().substring(0, len) + "...");
            result = sysLogMapper.insert(sysLog);
        }
        return result > 0;
    }

    @Override
    public List<SysLog> data(LoggingType loggingType, LocalDateTime startTime, LocalDateTime endTime) {
        return sysLogMapper.selectList(loggingType, startTime, endTime);
    }

    @Override
    public SysLog getById(String id) {
        return sysLogMapper.selectById(id);
    }

    @Override
    public List<SysLog> selectTopLoginLog(String operateName) {
        return sysLogMapper.selectTopLoginLog(operateName);
    }

}
